//
//  AdService.m
//  alotOf
//
//  Created by Mac_Black_Mini on 2025/9/5.
//

#import "AdService.h"
#import <ADSDK/SuperADLib.h>

@interface AdService ()

@property (nonatomic, assign) BOOL isVip;
@property (nonatomic, copy) NSString *advertisingConfig; // 广告远程配置

@end

@implementation AdService

static AdService *instance;

+ (instancetype)shared {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [[super allocWithZone:NULL] init];
    });
    return instance;
}

+ (instancetype)allocWithZone:(struct _NSZone *)zone {
    return [self shared];
}

#pragma mark - 外部接口
- (void)initializeAd {
    // 初始化广告（与原逻辑一致）
    NSDictionary *adDatas = @{
        @"version": Tools.appVersion,
        @"package_id": Tools.bundleId,
        @"uuid": Tools.deviceId
    };
    [SuperADLib.shared loadAdsWithDatas:adDatas complete:^(BOOL result) {
        if (!result) [SuperADLib.shared reloadAdsDatas];
    }];
}

- (void)setIsVip:(BOOL)isVip {
    self.isVip = isVip;
}

- (void)showAdWithConfig:(NSString *)config atViewController:(UIViewController *)vc {
    // VIP不显示广告
    if (self.isVip) return;
    if (!config || vc == nil) return;
    
    // 解析广告配置（格式：1/2 → 显示开关/广告类型）
    NSArray *configs = [config componentsSeparatedByString:@"/"];
    if (configs.count < 2) return;
    BOOL needShow = [configs.firstObject boolValue];
    if (!needShow) return;
    NSInteger adType = [configs[1] integerValue];
    
    // 主线程显示广告
    dispatch_async_safe_main(^{
        switch (adType) {
            case 1: // 开屏广告
                {
                    [SuperADLib.shared showOpenAdAt:vc complete:^(BOOL result) {
                        NSLog(@"Ad-> 开屏广告显示%@", result ? @"成功" : @"失败");
                    }];
                }
                break;
            case 2: // 插屏广告
            {
                [SuperADLib.shared showInsertAdAt:vc complete:^(BOOL result) {
                    NSLog(@"Ad-> 插屏广告显示%@", result ? @"成功" : @"失败");
                }];
            }
                break;
            case 3: // 激励广告
                {
                    [SuperADLib.shared showRewardAdAt:vc complete:^(BOOL result) {
                        NSLog(@"Ad-> 激励广告显示%@", result ? @"成功" : @"失败");
                    }];
                    break;
                }
            default:
                break;
        }
    });
}

#pragma mark - 外部配置设置（可选，若需更新广告远程配置）
- (void)setAdvertisingConfig:(NSString *)advertisingConfig {
    if ([self.advertisingConfig isEqualToString:advertisingConfig]) return;
    self.advertisingConfig = advertisingConfig;
    // 加载远程广告配置（与原逻辑一致）
    [SuperADLib.shared loadRemoteDatas:@{@"advertising": advertisingConfig}];
}

@end
